package nickthissen.iracing.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import nickthissen.iracing.common.DataLoader;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.common.Redirect;
import nickthissen.iracing.common.ServiceLogging;
import nickthissen.iracing.common.Task;
import nickthissen.iracing.datamodels.PrivateMessage;
import nickthissen.iracing.datamodels.PrivateMessageItem;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.PmParser;

/**
 * Created by Nick on 2-6-13.
 */
public class PrivateMessageActivity extends TaskActivity
{
    private static final String PMITEM = "PMITEM";
    private static final String PM = "PM";
    private static final String URL = "URL";

    private String url;
    private PrivateMessageItem pmItem;
    private PrivateMessage pm;

    private ProgressDialog dialog;

    private TextView lblAuthor;
    private WebView webContent;

    public static final int REPLYPM = 1;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pm);

        lblAuthor = (TextView) this.findViewById(R.id.lblAuthor);
        webContent = (WebView) this.findViewById(R.id.webContent);

        webContent.setWebViewClient(new PmWebViewClient(this));
        webContent.getSettings().setJavaScriptEnabled(true);

        Bundle extras = savedInstanceState;
        if (extras == null)
        {
            Intent i = this.getIntent();
            extras = i.getExtras();
        }
        Object pmItemObj = extras.getSerializable(PMITEM);
        if (pmItemObj == null) return;
        pmItem = (PrivateMessageItem) pmItemObj;

        SherlockUtils.setMultilineTitle(this, pmItem.Title);
        lblAuthor.setText(pmItem.Author);

        this.loadPm(pmItem.Url);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getSupportMenuInflater().inflate(R.menu.pm, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
            case R.id.mnuReply:
                this.reply();
                return true;
            case R.id.mnuDelete:
                this.delete();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putSerializable(PMITEM, pmItem);
        outState.putSerializable(PM, pm);
    }

    @Override
    public void onRestoreInstanceState(Bundle state)
    {
        pmItem = (PrivateMessageItem) state.getSerializable(PMITEM);
        pm = (PrivateMessage) state.getSerializable(PM);
        super.onRestoreInstanceState(state);
    }

    public static Intent getIntent(Context context, PrivateMessageItem item)
    {
        Intent i = new Intent(context, PrivateMessageActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(PMITEM, item);
        i.putExtras(bundle);
        return i;
    }

    @Override
    protected Task<?> createTask()
    {
        return new Task<String>(this, loader);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {
        state.putString(URL, url);
    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return state.getString(URL);
    }

    private void loadPm(String pmUrl)
    {
        url = pmUrl;

        dialog = ProgressDialog.show(this, "Loading", "Loading PM...");
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);

        this.runTask(pmUrl);

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface d)
            {
                task.cancel(true);
                d.dismiss();
            }
        });

        ServiceLogging.logPageRequest(this, url);
    }

    private void setContents()
    {
        lblAuthor.setText(pmItem.Author + ", " + pm.Date);

        StringBuilder builder = new StringBuilder();

        // HTML
        builder.append("<html><head><link rel=\"stylesheet\" href=\"file:///android_asset/style.css\" type=\"text/css\">");
        builder.append("</link></head><body>");
        builder.append(getPmBody());
        builder.append("</body></html>");

        webContent.loadDataWithBaseURL("file:///android_asset/", builder.toString(), "text/html", "utf-8", null);
    }

    private String getPmBody()
    {
        StringBuilder builder = new StringBuilder();
        builder.append("<div class=\"post\">");
        builder.append("<div class=\"pmcontent\">");
        builder.append(pm.Content);
        builder.append("</div></div>");
        return builder.toString();
    }

    private void reply()
    {
        Intent intent = SendPmActivity.getIntent(this, PostActivity.TYPE_REPLYPM, pm, pmItem);
        this.startActivityForResult(intent, REPLYPM);
    }

    private void delete()
    {
        Toast.makeText(this, "This feature is not yet implemented!", Toast.LENGTH_LONG).show();
    }

    private DataLoader<String> loader = new DataLoader<String>()
    {
        @Override
        public Result getData(String in)
        {
            Result result = Networking.getPm(this.getContext(), in);
            if (result.Success)
            {
                String source = (String)result.Object;
                return new PmParser().parse(source);
            }
            else
            {
                return result;
            }
        }

        @Override
        public void onFinished(Result out)
        {
            if (out.Success)
            {
                pm = (PrivateMessage)out.Object;
            }
            else
            {
                pm = new PrivateMessage();
                Error.fromResult(out).report(this.getContext());
            }

            setContents();
            if (dialog != null)
            {
                dialog.dismiss();
                dialog = null;
            }
        }
    };


    private class PmWebViewClient extends WebViewClient
    {
        private PrivateMessageActivity activity;
        private final String IMG_ATTACH_URL = "http://members.iracing.com/jforum/posts/downloadAttach/";
        private final String FORUM_URL = "http://members.iracing.com/jforum/";
        private final String FORUMLIST_URL = "http://members.iracing.com/jforum/forums/list.page";

        public PmWebViewClient(PrivateMessageActivity activity)
        {
            this.activity = activity;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
//			else if (url.startsWith(IMG_ATTACH_URL))
//			{
//				activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//			}
            if (url.startsWith(FORUM_URL))
            {
                Uri uri = Uri.parse(url);
                Redirect redirect = Redirect.handleData(uri);
                if (redirect != null)
                {
                    Redirect.loadRedirect(activity, redirect);
                }
            }
            else
            {
                activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            }
            return true;
        }
    }
}
